const {db} = require("../../config/dbconfig");

// 递归构建树结构
function buildTree(comments, articleId, parentId = null) {
    const tree = [];
    for (const comment of comments) {
        if (comment.parent_comment_id === parentId && comment.article_id === articleId) {
            const children = buildTree(comments, articleId, comment.comment_id);
            if (children.length) {
                comment.children = children;
            }
            tree.push(comment);
        }
    }
    return tree;
}

exports.getAllArticles = async (req, res, next) => {
    // 查询所有文章
    const articlesSql = `
    SELECT
        id AS article_id,
        title AS article_title,
        content AS article_content,
        image_url AS article_image_url,
        created_at AS article_created_at,
        updated_at AS article_updated_at,
        published_at AS article_published_at,
        ip_address AS article_ip_address,
        likes AS article_likes
    FROM
        Articles
    ORDER BY
            created_at DESC;
  `;

    // 查询所有评论
    const commentsSql = `
    SELECT
        c.id AS comment_id,
        c.content AS comment_content,
        c.created_at AS comment_created_at,
        c.likes AS comment_likes,
        cu.username AS comment_author_username,
        cu.email AS comment_author_email,
        c.parent_comment_id,
        a.id AS article_id
    FROM
        Comments c
    JOIN
        Users cu ON c.author_id = cu.id
    JOIN
        Articles a ON c.article_id = a.id
    ORDER BY
        c.created_at DESC;
  `;
    // 执行查询
    db.query(articlesSql, (error, articlesResults) => {
        if (error) {
            console.error('Error fetching articles data:', error);
            res.status(500).json({error: 'Error fetching articles data'});
        } else {
            // 执行查询
            db.query(commentsSql, (error, commentsResults) => {
                if (error) {
                    console.error('Error fetching comments data:', error);
                    res.status(500).json({error: 'Error fetching comments data'});
                } else {
                    // 构建文章及其评论树结构
                    const articles = [];
                    for (const article of articlesResults) {
                        article.comments = buildTree(commentsResults, article.article_id);
                        articles.push(article);
                    }
                    res.cc(articles);
                }
            });
        }
    });
}

// 添加文章
exports.addArticle = async (req, res, next) => {
    const {title, content, imageUrl, author_id, address} = req.body;
    // 执行插入操作
    db.query(
        'INSERT INTO Articles (title, content, image_url,author_id,ip_address) VALUES (?, ?, ?,?,?)',
        [title, content, imageUrl, author_id, address],
        (error, results) => {
            if (error) {
                console.error('Error adding article:', error);
                res.status(500).json({error: 'Error adding article'});
            } else {
                res.status(201).json({code: 200, message: 'Article added successfully', articleId: results.insertId});
            }
        }
    );
}
exports.getArticleById = async (req, res, next) => {
    const articleId = req.params.articleId;
    // 查询文章信息
    const articleSql = 'SELECT * FROM Articles WHERE id = ?';
    db.query(articleSql, [articleId], (error, articleResults) => {
        if (error) {
            console.error('Error fetching article:', error);
            return res.status(500).json({error: 'Error fetching article'});
        }

        if (articleResults.length === 0) {
            return res.status(404).json({error: 'Article not found'});
        }

        const article = articleResults[0];
        const articleData = {
            id: article.id,
            title: article.title,
            content: article.content,
            image_url: article.image_url,
            created_at: article.created_at,
            likes: article.likes,
            comments: []
        };

        // 查询一级评论
        const commentSql = `
      SELECT Comments.id, Comments.content, Comments.author_id, 
             Comments.created_at, Users.username
      FROM Comments
      INNER JOIN Users ON Comments.author_id = Users.id
      WHERE Comments.article_id = ? AND Comments.parent_comment_id IS NULL
    `;
        db.query(commentSql, [articleId], (error, commentResults) => {
            if (error) {
                console.error('Error fetching comments:', error);
                return res.status(500).json({error: 'Error fetching comments'});
            }

            // 查询每个一级评论的二级评论
            const getSubComments = (parentCommentId) => {
                return new Promise((resolve, reject) => {
                    const subCommentSql = `
            SELECT Comments.id, Comments.content, Comments.author_id, 
                   Comments.created_at, Users.username
            FROM Comments
            INNER JOIN Users ON Comments.author_id = Users.id
            WHERE Comments.article_id = ? AND Comments.parent_comment_id = ?
          `;
                    db.query(subCommentSql, [articleId, parentCommentId], (error, subCommentResults) => {
                        if (error) {
                            console.error('Error fetching sub comments:', error);
                            reject(error);
                        } else {
                            resolve(subCommentResults);
                        }
                    });
                });
            };

            // 递归查询并组织评论树结构
            const buildCommentTree = async (comments) => {
                for (const comment of comments) {
                    const subComments = await getSubComments(comment.id);
                    if (subComments.length > 0) {
                        comment.subComments = subComments;
                        await buildCommentTree(subComments);
                    }
                }
            };

            // 构建评论树
            buildCommentTree(commentResults)
                .then(() => {
                    articleData.comments = commentResults;
                    res.json(articleData);
                })
                .catch(error => {
                    console.error('Error building comment tree:', error);
                    res.status(500).json({error: 'Error building comment tree'});
                });
        });
    });
}
// 删除文章
exports.deleteArticleByIds = async (req, res, next) => {
    const articleIds = req.body.articleIds;
    console.log(req.body)
    console.log(articleIds)
    if (!articleIds || !Array.isArray(articleIds) || articleIds.length === 0) {
        return res.status(400).json({error: 'Invalid article IDs'});
    }

    const sql = 'DELETE FROM Articles WHERE id IN (?)';
    db.query(sql, [articleIds], (error, results) => {
        if (error) {
            console.error('Error deleting articles:', error);
            return res.status(500).json({error: 'Error deleting articles'});
        }

        res.cc({message: 'Articles deleted successfully'});
    });

}

// 更新文章
exports.updateArticleById = async (req, res, next) => {
    const articleId = req.params.articleId;
    const {title, content, address, imageUrl, likes} = req.body;
    console.log(articleId, title, content, imageUrl, likes, req.body)
    const sql = 'UPDATE Articles SET title = ?, content = ?, image_url = ? ,likes = ? ,ip_address = ? WHERE id = ?';
    db.query(sql, [title, content, imageUrl, likes, address, articleId], (error, results) => {
        if (error) {
            console.error('Error updating article:', error);
            return res.status(500).json({error: 'Error updating article'});
        } else {
            res.cc({message: 'Article updated successfully'});
        }
    })
}
